package com.cssl.jianting;

import lombok.Getter;
import org.springframework.beans.factory.annotation.Autowired;
import utils.RedisUtil;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.util.ArrayList;
import java.util.List;

@WebListener
public class MyListener implements HttpSessionListener, ServletContextListener {
    @Getter
    private static ServletContext application;

    @Autowired
    private RedisUtil redisUtil;
    /**
     * @see,session创建
     */
    public void sessionCreated(HttpSessionEvent se)  {
        HttpSession session = se.getSession();
        session.setMaxInactiveInterval(30);
    }

    /**
     * @see,session销毁
     */
    public void sessionDestroyed(HttpSessionEvent se)  {
        HttpSession session = se.getSession();
        //获得当前用户
        String user = (String)session.getAttribute("user");
        System.out.println("session销毁:"+user);

        redisUtil.del("name");

        //获得所有在线用户
        List<String> users = (List<String>)application.getAttribute("users");
        if(users.contains(user)) {
            users.remove(user);
        }
    }

    /**
     * @see,application销毁
     */
    public void contextDestroyed(ServletContextEvent sce)  {
        System.out.println("application销毁");
    }

    /**
     * @see,application创建
     */
    public void contextInitialized(ServletContextEvent sce)  {
        application = sce.getServletContext();
        System.out.println("application创建:");
        application.setAttribute("users", new ArrayList<String>());
    }
}
